package com.yixin.my.shop.web.be.service.impl;

import com.yixin.my.shop.domain.TbUser;
import com.yixin.my.shop.web.be.dao.TbUserDao;
import com.yixin.my.shop.web.be.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
@Service
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    private TbUserDao tbUserDao;

    @Override
    public List<TbUser> selectAll() {
        return tbUserDao.selectAll();
    }

    @Override
    public TbUser login(String username, String password) {
        TbUser tbUser = tbUserDao.getByUsername(username);
        if (tbUser != null){
            //获得密码
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            if (tbUser.getPassword().equals(md5Password)){
                return tbUser;
            }
        }
        return null;
    }

    @Override
    public List<TbUser> search(TbUser tbUser) {
        return tbUserDao.search(tbUser);
    }

    @Override
    public TbUser getById(Long id) {
        if (id != null){
            return tbUserDao.getById(id);
        }
        return null;
    }

    @Override
    public void save(TbUser tbUser) {
        Date date = new Date();
        tbUser.setUpdated(date);
        String md5Password = DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes());
        tbUser.setPassword(md5Password);
        if (tbUser.getId() != null){
            //跟新数据
            tbUserDao.update(tbUser);
        } else {
            //新建数据
            tbUser.setCreated(date);
            tbUserDao.creat(tbUser);
        }
    }
}
